package com.zgzg.shop.pay.base.utils;

import cn.hutool.core.lang.Validator;
import com.zgzg.shop.pay.base.enums.ApiCode;
import com.zgzg.shop.pay.base.exception.CustomException;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.util.UriComponentsBuilder;

import javax.validation.constraints.NotBlank;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: qiuyu
 * @Date: 2021/7/30
 **/
public class UrlUtils {

    public static String getFromHttpUrl(String url, Map<String, ?> params) {
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
        if (!CollectionUtils.isEmpty(params)) {
            for (Map.Entry<String, ?> entry : params.entrySet()) {
                //构建查询参数
                if(entry.getValue() instanceof List){
                    builder.queryParam(entry.getKey(), (List)entry.getValue());
                }else if (entry.getValue().getClass().isArray()){
                    builder.queryParam(entry.getKey(), Arrays.asList(entry.getValue()));
                }
            }
            return builder.build().toString();
        }
        return url;
    }

    /**
     * @Description: 拼接完整的url
     * @Author: qy
     * @Date: 2021/8/2 9:13
     **/
    public static String getForWholeUrl(String url, Map<String, ?> uriVariables) {
        StringBuilder wholeUrl = new StringBuilder(url);
        wholeUrl.append("?");
        for (Map.Entry<String, ?> entry : uriVariables.entrySet()) {
            wholeUrl.append(entry.getKey());
            wholeUrl.append("=");
            wholeUrl.append(entry.getValue());
            wholeUrl.append("&");
        }
        return wholeUrl.substring(0, wholeUrl.length() - 1);
    }

    /**
     * @Description: 拼接完整的带参url
     * @Author: qy
     * @Date: 2021/8/2 9:13
     **/
    public static String getForParameterWholeUrl(String url, Map<String, ?> uriVariables) {
        StringBuilder wholeUrl = new StringBuilder(url);
        wholeUrl.append("?");
        if (uriVariables != null) {
            for (Map.Entry<String, ?> entry : uriVariables.entrySet()) {
                wholeUrl.append(entry.getKey());
                wholeUrl.append("=");
                wholeUrl.append("{");
                wholeUrl.append(entry.getKey());
                wholeUrl.append("}");
                wholeUrl.append("&");
            }
        }
        return wholeUrl.substring(0, wholeUrl.length() - 1);
    }

    /**
     * @Description: 获取URl资源
     * @Author: qy
     * @Date: 2021/8/20 21:54
     * @param spec: the String to parse as a URL
     * @param resourceType: 网络资源类型，类似于网络资源的另存为
     * @return: org.springframework.core.io.InputStreamResource
     **/
    public static InputStreamResource getUrlResource(@NotBlank String spec, ResourceType resourceType) {
        InputStreamResource inputStreamResource;
        try {
            URLConnection conn = new URL(spec).openConnection();
            inputStreamResource = new InputStreamResource(conn.getInputStream()) {
                @Override
                public long contentLength() {
                    return conn.getContentLength();
                }

                @Override
                public String getFilename() {
                    return UUID.randomUUID().toString() + "." + resourceType.getType();
                }
            };
        } catch (IOException e) {
            throw new CustomException(ApiCode.SERVER_ERROR,"getUrlResource解析网络地址出错。请核对资源地址，保证可以在网络中访问。");
        }
        return inputStreamResource;
    }

    /**
     * 直接获取网络文件的md5值
     * @param urlStr: 网络资源url
     * @return 资源摘要
     */
    public static String md5(String urlStr) {
        Assert.hasText(urlStr, "网络资源url不存在。");
        String md5 = null;
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            DataInputStream in = new DataInputStream(conn.getInputStream());
            md5 = DigestUtils.md5Hex(in);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return md5;
    }

//    public static void main(String[] args) {
//        System.out.println(UrlUtils.md5("http://inews.gtimg.com/newsapp_bt/0/13936881745/641"));
//    }


    /**
     * 获取uri
     **/
    public static String getBaseURI(String url) {
        if (Validator.isUrl(url)) {
            String[] urlParts = url.split("\\?");
            return urlParts[0];
        }
        return url;
    }

    /**
     * 获取url参数
     **/
    public static Map<String, String> getParam(String url) {
        Map<String, String> map = new HashMap<>();
        if (Validator.isUrl(url)) {
            String[] urlParts = url.split("\\?");
            //没有参数
            if (urlParts.length == 1) {
                return map;
            }
            //有参数
            String[] params = urlParts[1].split("&");
            for (String param : params) {
                String[] keyValue = param.split("=");
                map.put(keyValue[0], keyValue[1]);
            }
        }
        return map;
    }

    public enum ResourceType {
        DEFAULT_FILE("file"),
        IMAGE_PNG("png"),
        IMAGE_JPG("jpg"),
        VOICE_MP3("mp3"),
        VIDEO_MP4("mp4");

        private final String type;

        ResourceType(String type) {
            this.type = type;
        }

        public String getType() {
            return type;
        }
    }

}
